package dai.samples.shiro.converter;

import com.alibaba.fastjson.JSON;
import dai.samples.shiro.entity.MySession;
import org.apache.shiro.session.mgt.SimpleSession;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashMap;

/**
 * 一个简单的类转换操作
 */
public class MySessionConverter {

    /**
     * 将simpleSession转换成自定义的Session
     * @param session
     * @return
     */
    public static MySession toMySession(SimpleSession session) {
        if (session == null) {
            return null;
        }
        MySession mySession = new MySession();
        mySession.setId((String) session.getId());
        mySession.setHost(session.getHost());
        Timestamp timestampStart = new Timestamp(session.getStartTimestamp().getTime());
        mySession.setStartTimestamp(timestampStart);
        Timestamp timestampLast = new Timestamp(session.getLastAccessTime().getTime());
        mySession.setLastAccessTime(timestampLast);
        mySession.setTimeout(session.getTimeout());
        mySession.setExpired(session.isExpired());
        Collection<Object> attributeKeys = session.getAttributeKeys();
        HashMap<Object,Object> attribute = new HashMap<>();
        attributeKeys.forEach(item -> {
            Object attribute1 = session.getAttribute(attribute);
            attribute.put(item,attribute1);
        });
        mySession.setAttributeJson(JSON.toJSONString(attribute));
        return mySession;
    }

    /**
     * 将自定义的Session转换成simpleSession
     * @param session
     * @return
     */
    public static SimpleSession toSimpleSession(MySession session) {
        if (session == null) {
            return null;
        }
        SimpleSession simpleSession = new SimpleSession();
        simpleSession.setId(session.getId());
        simpleSession.setAttributes(session.getAttributes());
        simpleSession.setExpired(session.isExpired());
        simpleSession.setHost(session.getHost());
        simpleSession.setLastAccessTime(session.getLastAccessTime());
        simpleSession.setStartTimestamp(session.getStartTimestamp());
        simpleSession.setStopTimestamp(session.getStopTimestamp());
        simpleSession.setTimeout(session.getTimeout());
        return simpleSession;
    }

}
